import time
import threading
import logging
from database.crud import get_upcoming_events, update_reminded_flag
from utils.time_utils import format_time
from utils.config import REMINDER_INTERVAL

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='[REMINDER] %(asctime)s - %(message)s',
    datefmt='%H:%M:%S'
)

def run_reminder_service():
    """运行后台提醒服务（每分钟检查一次）"""
    print("\n[REMINDER] ✅ Reminder service started (daemon thread)")
    print(f"[REMINDER] Checking for upcoming events every {REMINDER_INTERVAL} seconds...\n")
    
    while True:
        try:
            # 获取即将提醒的事件
            upcoming_events = get_upcoming_events()
            
            if upcoming_events:
                logging.info(f"Found {len(upcoming_events)} upcoming events")
                
                for event in upcoming_events:
                    event_id, title, desc, event_time, reminder_time, _, category, recurring_type, _ = event
                    formatted_time = format_time(event_time)
                    
                    # 触发提醒（控制台输出）
                    print(f"🔔 [REMINDER] {formatted_time} - {title}")
                    print(f"   Description: {desc}")
                    if category:
                        print(f"   Category: {category}")
                    if recurring_type:
                        print(f"   Recurring: {recurring_type}")
                    print()
                    
                    # 标记为已提醒
                    update_reminded_flag(event_id)
            
            # 每隔指定秒数检查
            time.sleep(REMINDER_INTERVAL)
            
        except Exception as e:
            logging.error(f"Service error: {str(e)}")
            time.sleep(5)  # 错误后等待5秒重试

if __name__ == "__main__":
    run_reminder_service()